﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class DALEdge : IDALEdge, IDisposable
    {
        private CarBatteryEntities context;
        private bool disposed = false;

        public DALEdge(CarBatteryEntities context)
        {
            this.context = context;
        }

        public void AddEdges(List<Edge> edges)
        {
            foreach (var edge in edges)
                context.Edge.Add(edge);
        }

        public void RemoveEdge(Edge edge)
        {
            foreach (var e in LookUpEdges(edge.BatteryStation.name, edge.BatteryStation1.name))
                context.Edge.Remove(e);
        }
      
        public Edge FindEdge(string edgeFrom, string edgeTo)
        {
            return LookUpEdges(edgeFrom, edgeTo).FirstOrDefault();
        }

        private IQueryable<Edge> LookUpEdges(string edgeFrom, string edgeTo)
        {
            var edge =
                from edges in context.Edge.Include(e => e.BatteryStation).Include(e => e.BatteryStation1)
                where (
                    (edges.BatteryStation.name.Equals(edgeFrom) && edges.BatteryStation1.name.Equals(edgeTo)) ||
                    (edges.BatteryStation.name.Equals(edgeTo) && edges.BatteryStation1.name.Equals(edgeFrom))
                )
                select edges;

            return edge;
        }

        public IList<Edge> GetBatteryCenterEdges(string name)
        {
            var query = context.Edge.Include(e => e.BatteryStation).Include(e => e.BatteryStation1).Where(edge => edge.BatteryStation.name.Equals(name) || edge.BatteryStation1.name.Equals(name)).AsEnumerable().SelectMany(edge => new[] { edge, new Edge() { BatteryStation = edge.BatteryStation1, BatteryStation1 = edge.BatteryStation, distance = edge.distance } });
            
            return query.ToList();
        }

        public int Save()
        {
            return context.SaveChanges();
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                    context.Dispose();
            }

            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}